import json
import ASTTrans

# import user_guide


def analyze_ast(ast_data, feature_strings):
    """分析 AST 并对所有可能的字符串进行特征字符串匹配，允许一定容错率"""

    def recursive_check(node, current_path=''):
        if isinstance(node, dict):
            for key, value in node.items():
                new_path = f"{current_path}[{key}]" if current_path else f"[{key}]"
                if isinstance(value, str):
                    for category, strings in feature_strings.items():
                        for string in strings:
                            if is_close_match(value, string):
                                print(f"匹配描述：'{string}'\n疑似内容：'{category}'\n位置：'{new_path}'")
                                return True
                elif isinstance(value, dict) or isinstance(value, list):
                    found = recursive_check(value, new_path)
                    if found:
                        return True
        elif isinstance(node, list):
            for index, item in enumerate(node):
                new_path = f"{current_path}[{index}]" if current_path else f"[{index}]"
                if isinstance(item, dict) or isinstance(item, list):
                    found = recursive_check(item, new_path)
                    if found:
                        return True
        return False

    return recursive_check(ast_data)

    return recursive_check(ast_data)


def is_close_match(str1, str2):
    """判断两个字符串是否接近匹配"""
    if str2 in str1:
        return True
    else:
        m, n = len(str1), len(str2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m + 1):
            dp[i][0] = i
        for j in range(n + 1):
            dp[0][j] = j
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                cost = 0 if str1[i - 1] == str2[j - 1] else 1
                dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
        edit_distance = dp[m][n]
        longer_length = max(m, n)
        similarity = 1 - edit_distance / longer_length
        return similarity > 0.8


def load_json_ast(file_path):
    """从文件中加载 JSON 格式的 AST"""
    with open(file_path, 'r') as file:
        return json.load(file)


# 定义特征字符串字典
feature_strings = {
    "RAT_SIGNATURES": ["subprocess.Popen", "socket.socket", "shutil.copy", "shutil.move", "shutil.rmtree",
                       "pynput.keyboard",
                       "pyHook", "mss", "PIL.ImageGrab", "cv2.VideoCapture", "pygame.camera", "execCommand",
                       "encryptionKey", "dial", "getshell",
                       "net.Dial", "exec.Command|8080"],
    "CNC_SIGNATURES": ["http://c2-server.com", "AES", "RSA", "SSL", "TLS", "ping", "keep-alive",
                       "requests.post", "socket.send", "shutil.make_archive", "C2Server", "Botnet", "RemoteCommand",
                       "ControlChannel", "Beaconing",
                       "CallbackURL", "CommandExecution", "DataExfiltration", "MaliciousDomain", "TorNetwork",
                       "http.Get", "http.Post", "8080", "443",
                       "crypto/aes", "crypto/rsa"],
    "HIDDEN_EXECUTION_SIGNATURES": ["importlib.import_module", "getattr", "setattr", "delattr", "hasattr", "PIL.Image",
                                    "numpy",
                                    "cv2", "ctypes.windll", "ctypes.cdll", "pywin32", "time.sleep", "RunHidden",
                                    "HiddenProcess", "StealthMode",
                                    "SilentExecution", "BackgroundTask", "HiddenThread", "InvisibleWindow",
                                    "HiddenService", "UndocumentedAPI", "RootkitFunction",
                                    "syscall", "os/exec"],
    "MALICIOUS_SCRIPT_SIGNATURES": ["SubAutoOpen()", "SubDocument_Open()", "ExecuteExcel4Macro", "powershell.exe",
                                    "-NoProfile", "-ExecutionPolicyBypass", "getshell",
                                    "<script>", "setTimeout(", "WScript.Shell", "CreateObject", "Execute", "Run",
                                    "ShellExecute", "Send", "VBAProject", "Auto_Open",
                                    "Document_Open", "PowerShell", "Invoke-Expression", "DownloadString",
                                    "ExecuteCommand", "MacroVirus",
                                    "executeExternalCommand", "downloadFromURL"],
    "USER_PERMISSION_SIGNATURES": ["SetPrivilege", "C:\\Windows\\System32\\config\\SAM", "elevate", "privilege",
                                   "UACBypass", "DLLInjection",
                                   "ExploitVulnerability", "TokenImpersonation", "SetUID", "SudoVulnerability",
                                   "KernelExploit", "LocalPrivilegeEscalation",
                                   "ElevatePrivileges", "syscall.Syscall", "syscall.RawSyscall", "os.Chmod"],
    "DATA_THEFT_SIGNATURES": ["suspicious_domain.com", "FTP", "POST", "data_steal", "stolen_data", "keylogger",
                              "stealPassword", "exfiltrateData", "captureCredentials", "sniffNetwork", "remoteAccess",
                              "backdoor", "net.Dial",
                              "os.Open", "ioutil.ReadFile"],
    "CONCEALED_PASSAGE_SIGNATURES": ["ping-p", "nslookup", "curl", "curl-k", "ssh-R", "mailto:", "icmpExfiltration",
                                     "dnsTunneling",
                                     "httpStager", "tcpCovertChannel", "udpCovertChannel", "icmpCovertChannel",
                                     "dnsCovertChannel", "steganography", "port9999", "http.Header",
                                     "os.OpenFile"],
    "PERSISTENT_SIGNATURES": ["HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "schtasks/create", "sccreate",
                              "LoadLibrary",
                              "ActiveScriptEventConsumer", "StartupFolder", "RegistryRunKey", "ServiceCreation",
                              "ScheduledTask", "WMIEventSubscription", "LogonScript",
                              "DLLHijacking", "BootExecute", "ImageFileExecutionOptions", "os.StartProcess",
                              "registry.OpenKey", "os.Create", "os.WriteFile"],
    "POLYMORPHIC_SIGNATURES": ["AES_ENCRYPT", "DES_ENCRYPT", "RC4_ENCRYPT", "Blowfish_ENCRYPT", "EXEC_OBFUSCATED",
                               "EVAL_OBFUSCATED",
                               "COMPILE_OBFUSCATED", "XOR_SHELLCODE", "ADD_SHELLCODE", "SUB_SHELLCODE", "ROL_SHELLCODE",
                               "ROR_SHELLCODE", "DECRYPT_DYNAMIC", "DECODE_DYNAMIC",
                               "DECODEBYTES_DYNAMIC", "CreateRemoteThread", "maliciousserver", "encrypt_", "obfuscate_",
                               "C:\\Windows\\Temp\\", "randomstring.dll",
                               "encryptedPayload", "obfuscatedCode", "selfModifyingCode", "codeMutation",
                               "dynamicPayload", "polymorphicShellcode", "variantEngine",
                               "morphingEngine", "metamorphicCode", "crypto/rand", "reflect"],
    "MALICIOUS_UPGRADE_SIGNATURES": ["http://malicious-update-server.com", "https://evil-update.net",
                                     "update.malicious-domain.com",
                                     "download.evil-server.org", "importlib.import_module", "ctypes.CDLL",
                                     "ctypes.PyDLL", "mitmproxy", "Fiddler", "BurpSuite", "update.exe",
                                     "upgrader", "patch", "C:\\Users\\XXX\\AppData\\Local\\Temp\\random_update.exe",
                                     "patch.exe", "installer.exe", "downloader.exe", "updater.exe",
                                     "silentUpdate", "autoUpdate", "updateScript", "maliciousPayload", "http.Get",
                                     "http.Post", "os.WriteFile", "os.Rename"],
    "suspicious_signatures": ["os.system", "C:\\RAT\\config.dat", "exec", "eval", "eval(", "UACBypass", "Rootkit",
                              "C:\\Users\\Documents", "sniffNetwork", "CreateRemoteThread",
                              "WriteProcessMemory", "VirtualAllocEx", "NtUnmapViewOfSection", "RtlCreateUserThread",
                              "LdrLoadDll", "LdrGetProcedureAddress", "GetProcAddress", "LoadLibraryA",
                              "WinExec", "ShellExecute", "RegCreateKeyEx", "RegSetValueEx", "RegDeleteValue",
                              "RegDeleteKey", "SetWindowsHookEx", "EnumWindows", "FindWindow", "FindFirstFile",
                              "FindNextFile", "CopyFile", "MoveFile", "DeleteFile", "CreateFile", "WriteFile",
                              "ReadFile", "GetFileSize", "SetFilePointer", "GetFileAttributes", "SetFileAttributes"
        , "GetModuleHandle", "GetProcAddress", "VirtualAlloc", "VirtualProtect", "VirtualQuery", "MapViewOfFile",
                              "UnmapViewOfFile", "CreateFileMapping", "OpenFileMapping"
        , "CloseHandle", "DuplicateHandle", "WaitForSingleObject", "Sleep", "GetTickCount", "QueryPerformanceCounter",
                              "GetSystemTime", "GetLocalTime", "GetTimeZoneInformation"
        , "GetComputerName", "GetUserName", "GetCurrentProcess", "GetCurrentThread", "GetProcessHeap", "HeapAlloc",
                              "HeapFree", "HeapReAlloc", "HeapSize", "HeapValidate"
        , "HeapCompact", "HeapLock", "HeapUnlock", "HeapWalk", "HeapCreate", "HeapDestroy", "GlobalAlloc", "GlobalFree",
                              "GlobalReAlloc", "GlobalSize", "GlobalLock", "GlobalUnlock"
        , "GlobalFlags", "GlobalHandle", "LocalAlloc", "LocalFree", "LocalReAlloc", "LocalSize", "LocalLock",
                              "LocalUnlock", "LocalFlags", "LocalHandle", "VirtualAllocEx"
        , "VirtualFreeEx", "VirtualProtectEx", "VirtualQueryEx", "MapViewOfFileEx", "UnmapViewOfFileEx",
                              "CreateFileMappingEx", "OpenFileMappingEx", "CloseHandleEx", "DuplicateHandleEx"
        , "WaitForSingleObjectEx", "SleepEx", "GetTickCountEx", "QueryPerformanceCounterEx", "GetSystemTimeEx",
                              "GetLocalTimeEx", "GetTimeZoneInformationEx", "GetComputerNameEx"
        , "GetUserNameEx", "GetCurrentProcessEx", "GetCurrentThreadEx", "GetProcessHeapEx", "HeapAllocEx", "HeapFreeEx",
                              "HeapReAllocEx", "HeapSizeEx", "HeapValidateEx"
        , "HeapCompactEx", "HeapLockEx", "HeapUnlockEx", "HeapWalkEx", "HeapCreateEx", "HeapDestroyEx", "GlobalAllocEx",
                              "GlobalFreeEx", "GlobalReAllocEx", "GlobalSizeEx"
        , "GlobalLockEx", "GlobalUnlockEx", "GlobalFlagsEx", "GlobalHandleEx", "LocalAllocEx", "LocalFreeEx",
                              "LocalReAllocEx", "LocalSizeEx", "LocalLockEx", "LocalUnlockEx"
        , "LocalFlagsEx", "LocalHandleEx", "VirtualAllocExEx", "VirtualFreeExEx", "VirtualProtectExEx",
                              "VirtualQueryExEx", "MapViewOfFileExEx", "UnmapViewOfFileExEx"
        , "CreateFileMappingExEx", "OpenFileMappingExEx", "CloseHandleExEx", "DuplicateHandleExEx",
                              "WaitForSingleObjectExEx", "SleepExEx", "GetTickCountExEx", "QueryPerformanceCounterExEx"
        , "GetSystemTimeExEx", "GetLocalTimeExEx", "GetTimeZoneInformationExEx", "GetComputerNameExEx",
                              "GetUserNameExEx", "GetCurrentProcessExEx", "GetCurrentThreadExEx"
        , "GetProcessHeapExEx", "HeapAllocExEx", "HeapFreeExEx", "HeapReAllocExEx", "HeapSizeExEx", "HeapValidateExEx",
                              "HeapCompactExEx", "HeapLockExEx", "HeapUnlockExEx"
        , "HeapWalkExEx", "HeapCreateExEx", "HeapDestroyExEx", "GlobalAllocExEx", "GlobalFreeExEx", "GlobalReAllocExEx",
                              "GlobalSizeExEx", "GlobalLockExEx", "GlobalUnlockExEx"
        , "GlobalFlagsExEx", "GlobalHandleExEx", "LocalAllocExEx", "LocalFreeExEx", "LocalReAllocExEx", "LocalSizeExEx",
                              "LocalLockExEx", "LocalUnlockExEx", "LocalFlagsExEx"
        , "LocalHandleExEx", "VirtualAllocExExEx", "VirtualFreeExExEx", "VirtualProtectExExEx", "VirtualQueryExExEx",
                              "MapViewOfFileExExEx", "UnmapViewOfFileExExEx"
        , "CreateFileMappingExExEx", "OpenFileMappingExExEx", "CloseHandleExExEx", "DuplicateHandleExExEx",
                              "WaitForSingleObjectExExEx", "SleepExExEx", "GetTickCountExExEx"
        , "QueryPerformanceCounterExExEx", "GetSystemTimeExExEx", "GetLocalTimeExExEx", "GetTimeZoneInformationExExEx",
                              "GetComputerNameExExEx", "GetUserNameExExEx"
        , "GetCurrentProcessExExEx", "GetCurrentThreadExExEx", "GetProcessHeapExExEx", "HeapAllocExExEx",
                              "HeapFreeExExEx", "HeapReAllocExExEx", "HeapSizeExExEx", "HeapValidateExExEx"
        , "HeapCompactExExEx", "HeapLockExExEx", "HeapUnlockExExEx", "HeapWalkExExEx", "HeapCreateExExEx",
                              "HeapDestroyExExEx", "GlobalAllocExExEx", "GlobalFreeExExEx"
        , "GlobalReAllocExExEx", "GlobalSizeExExEx", "GlobalLockExExEx", "GlobalUnlockExExEx", "GlobalFlagsExExEx",
                              "GlobalHandleExExEx", "LocalAllocExExEx", "LocalFreeExExEx"
        , "LocalReAllocExExEx", "LocalSizeExExEx", "LocalLockExExEx", "LocalUnlockExExEx", "LocalFlagsExExEx",
                              "LocalHandleExExEx", "VirtualAllocExExExEx", "VirtualFreeExExExEx"
        , "VirtualProtectExExExEx", "VirtualQueryExExExEx", "MapViewOfFileExExExEx", "UnmapViewOfFileExExExEx",
                              "CreateFileMappingExExExEx", "OpenFileMappingExExExEx"
        , "CloseHandleExExExEx", "DuplicateHandleExExExEx", "WaitForSingleObjectExExExEx", "SleepExExExEx",
                              "GetTickCountExExExEx", "QueryPerformanceCounterExExExEx"
        , "GetSystemTimeExExExEx", "GetLocalTimeExExExEx", "GetTimeZoneInformationExExExEx", "GetComputerNameExExExEx",
                              "GetUserNameExExExEx", "GetCurrentProcessExExExEx"
        , "GetCurrentThreadExExExEx", "GetProcessHeapExExExEx", "HeapAllocExExExEx", "HeapFreeExExExEx",
                              "HeapReAllocExExExEx", "HeapSizeExExExEx", "HeapValidateExExExEx"
        , "HeapCompactExExExEx", "HeapLockExExExEx", "HeapUnlockExExExEx", "HeapWalkExExExEx", "HeapCreateExExExEx",
                              "HeapDestroyExExExEx", "GlobalAllocExExExEx"
        , "GlobalFreeExExExEx", "GlobalReAllocExExExEx", "GlobalSizeExExExEx", "GlobalLockExExExEx",
                              "GlobalUnlockExExExEx", "GlobalFlagsExExExEx", "GlobalHandleExExExEx"
        , "LocalAllocExExExExEx", "LocalFreeExExExExEx", "LocalReAllocExExExExEx", "LocalSizeExExExExEx",
                              "LocalLockExExExExEx", "LocalUnlockExExExExEx", "LocalFlagsExExExExEx"
        , "LocalHandleExExExExEx", "VirtualAllocExExExExExEx", "VirtualFreeExExExExExEx", "VirtualProtectExExExExExEx",
                              "VirtualQueryExExExExExEx", "MapViewOfFileExExExExExEx"
        , "UnmapViewOfFileExExExExExEx", "CreateFileMappingExExExExExEx", "OpenFileMappingExExExExExEx",
                              "CloseHandleExExExExExEx", "DuplicateHandleExExExExExEx",
                              "WaitForSingleObjectExExExExExEx"
        , "SleepExExExExExEx", "GetTickCountExExExExExEx", "QueryPerformanceCounterExExExExExEx",
                              "GetSystemTimeExExExExExEx", "GetLocalTimeExExExExExEx",
                              "GetTimeZoneInformationExExExExExEx"
        , "GetComputerNameExExExExExEx", "GetUserNameExExExExExEx", "GetCurrentProcessExExExExExEx",
                              "GetCurrentThreadExExExExExEx", "GetProcessHeapExExExExExEx", "HeapAllocExExExExExEx"
        , "HeapFreeExExExExExEx", "HeapReAllocExExExExExEx", "HeapSizeExExExExExEx", "HeapValidateExExExExExEx",
                              "HeapCompactExExExExExEx", "HeapLockExExExExExEx", "HeapUnlockExExExExExEx"
        , "HeapWalkExExExExExEx", "HeapCreateExExExExExEx", "HeapDestroyExExExExExEx", "GlobalAllocExExExExExEx",
                              "GlobalFreeExExExExExEx", "GlobalReAllocExExExExExEx"
        , "GlobalSizeExExExExExEx", "GlobalLockExExExExExEx", "+=+=+"]
}


def main(json_file_path):
    # 加载 JSON 格式的 AST
    ast_data = load_json_ast(json_file_path)
    # print(ast_data)
    # 分析 AST 并进行特征字符串匹配
    is_malicious = analyze_ast(ast_data, feature_strings)

    if is_malicious:
        print("检测到木马后门模式！")
    else:
        print("未检测到木马后门模式。")


if __name__ == "__main__":
    path='hello.java'
    ASTTrans.get_AST_json(path)
    json_file_path = r'data.json'  # user_guide.program_road  # 替换为实际的 JSON 文件路径
    main(json_file_path)